package com.itbupt.eat.common;


import org.springframework.beans.factory.annotation.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author BUPT-Dingchang
 * @Create 2024/4/30 10:34
 * ClassName: CommonController
 * Description:
 */

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

     // 获取配置文件中的存储路径
    @Value("${reggie.path}")
    private String basePath;


    /**
     * 文件上传
     * @param file 文件
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        // file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删除

        // 1.获取原始文件名
        String originalFilename = file.getOriginalFilename();
        // 2.获取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 3.生成新的文件名
        String fileName = UUID.randomUUID().toString() + suffix;

        // 4.创建目录对象
        File dir = new File(basePath);
        // 5.判断目录是否存在
        if(!dir.exists()) {
            // 6.不存在则创建
            dir.mkdir();
        }

        try {
            // 转存
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 7.返回文件名
        return R.success(fileName);

    }


    /**
     * 文件下载
     * @param name  文件名
     * @param response  响应对象
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        FileInputStream fis = null;
        ServletOutputStream os = null;

        try {
            // 输入流
            fis = new FileInputStream(basePath + name);
            // 输出流
            os = response.getOutputStream();

            byte[] buffer = new byte[1024];
            int len = 0;
            while((len = fis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
                os.flush();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭流
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                    e.printStackTrace();
                }

            try {
                if(os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
